package com.example.crawlerjava.controller;

import com.example.crawlerjava.constant.CacheKey;
import com.example.crawlerjava.service.crawler.CrawlerStrategy;
import com.example.crawlerjava.entity.BaseEntity;
import com.example.crawlerjava.entity.UploadEntity;
import com.example.crawlerjava.service.upload.UploadStrategy;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

@Tag(name = "爬虫接口")
@RestController
@RequestMapping("/crawler")
@Slf4j
public class CrawlerController {

    @Resource(name = "ncatCrawler")
    private CrawlerStrategy crawlerStrategy;
    @Resource
    private UploadStrategy uploadStrategy;

    @Operation(summary = "搜索资源接口")
    @GetMapping("/search")
    public List<BaseEntity> index(@RequestParam("searchKey") String searchKey) {
        return crawlerStrategy.search(searchKey);
    }

    @Operation(summary = "获取资源详情")
    @GetMapping("/getDetail")
    public BaseEntity getDetail(@RequestParam("detailUrl") String detailUrl) {
        return crawlerStrategy.getDetail(detailUrl);
    }

    /**
     * 这个接口主要是上传本机文件到线服务器，然后通过返回的字符串去调用 /crawler/getUploadResult接口获取下载链接
     * @param uploadFilePath
     * @return
     */
    @Operation(summary = "上传接口")
    @GetMapping("/upload")
    public String upload(@RequestParam("uploadFilePath") String uploadFilePath) {
        String queryId = UUID.randomUUID().toString();
        uploadStrategy.upload(uploadFilePath, CacheKey.DOWNLOAD_KEY + queryId);
        return CacheKey.DOWNLOAD_KEY + queryId;
    }

    @Operation(summary = "获取上传结果")
    @GetMapping("/getUploadResult")
    public UploadEntity getUploadResult(@Parameter(description = "查询key", example = "download_keyf2fb1c1e-58f6-4bf0-85b6-7f13c839d528")
                                        @RequestParam("queryKey") String queryKey) {
        return uploadStrategy.getUploadResult(queryKey);
    }
}
